package cn.timeapi.Applet.Mall.CatSquare.controller.backend;

import cn.timeapi.Applet.Mall.CatSquare.common.Const;
import cn.timeapi.Applet.Mall.CatSquare.common.Conversation;
import cn.timeapi.Applet.Mall.CatSquare.common.ParamsNotNull;
import cn.timeapi.Applet.Mall.CatSquare.common.ServerResponse;
import cn.timeapi.Applet.Mall.CatSquare.entity.Product;
import cn.timeapi.Applet.Mall.CatSquare.service.IFileService;
import cn.timeapi.Applet.Mall.CatSquare.service.IProductService;
import cn.timeapi.Applet.Mall.CatSquare.util.PropertiesUtil;
import cn.timeapi.Applet.Mall.CatSquare.service.IManagementAccountService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 描述:后台商品管理
 * @author Vincent Vic
 * create 2020-02-17 14:37
 */
@Api("/manage/product/")
@RestController
@RequestMapping("/manage/product/")   //请求地址设置
public class ProductManageController {

    @Autowired
    private IManagementAccountService managementAccountService;


    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;

    //商品保存
    @ApiOperation("商品保存")
    @PostMapping("save")
    public ServerResponse  productSave(HttpSession session,@ApiParam("商品属性") Product product){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        return iProductService.SaveOrUptateProduct(product);
    }

    //商品上下架
    @ApiOperation("商品上下架")
    @PostMapping("setStatus")
    public ServerResponse  setSaleStatus(HttpSession session, @ApiParam("商品id") @ParamsNotNull Integer productId, @ApiParam("上下架状态（0/1）") @ParamsNotNull Integer status){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        return iProductService.setSaleStatus(productId,status);
    }

    //获取产品详情
    @ApiOperation("获取产品详情")
    @PostMapping("getDetail")
    @ResponseBody   //自动序列化Json
    public ServerResponse  getDetail(HttpSession session,@ApiParam("商品id") @ParamsNotNull Integer productId){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        return iProductService.manageProductDetail(productId);
    }

    //获取产品列表
    @ApiOperation("获取产品列表")
    @PostMapping("getList")
    @ResponseBody   //自动序列化Json
    public ServerResponse  getList(HttpSession session,@ApiParam("分页起始 默认1")  @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@ApiParam("分页个数 默认0") @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        return iProductService.getProductList(pageNum,pageSize);
    }

    //获取产品列表
    @ApiOperation("获取产品列表")
    @PostMapping("search")
    @ResponseBody   //自动序列化Json
    public ServerResponse  productSearch(HttpSession session, @ApiParam("商品名称") String productName,@ApiParam("商品id") Integer productId,@ApiParam("分页起始 默认1") @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@ApiParam("分页个数 默认10") @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        return iProductService.searchProduct(productName,productId,pageNum,pageSize);
    }



    //获取文件上传
    @ApiOperation("获取图片文件上传")
    @PostMapping("img/upload")
    @ResponseBody   //自动序列化Json
    public ServerResponse upload(HttpSession session,@ApiParam("文件") @RequestParam(value = "upload_file",required = false) MultipartFile file,@ApiParam("request") HttpServletRequest request){
        ServerResponse response = Conversation.checkAdminRole(session);
        if (!response.isSuccess()) {
            return response;
        }
        //采用ftp转存机制
        String path = request.getSession().getServletContext().getRealPath("upload");
        String suffix = "img";
        //String path = PathUtil.getUploadResources() + "img";
        if (path == null) {
            return ServerResponse.error("资源路径错误");
        }
        ServerResponse targetFileName = iFileService.upload(file,path,suffix);
        //检查上传状态
        if (!targetFileName.isSuccess()) {
            return targetFileName;
        }

        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+"img/"+targetFileName.getMsg();
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName.getMsg());
        fileMap.put("url",url);
        return ServerResponse.success(fileMap);
    }

    //获取富文本文件上传
    @ApiOperation("获取富文本文件上传")
    @PostMapping("richtext_img_upload")
    @ResponseBody   //自动序列化Json
    public Map richtextImgUpload(HttpSession session, @ApiParam("文件") @RequestParam(value = "upload_file",required = false) MultipartFile file,@ApiParam("request")  HttpServletRequest request, @ApiParam("response") HttpServletResponse response){
        Map resultMap = Maps.newHashMap();
        ServerResponse responses = Conversation.checkAdminRole(session);
        if (!responses.isSuccess()){
            resultMap.put("success",false);
            resultMap.put("msg","未登录/无权限");
            return resultMap;
        }
        //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
//        {
//            "success": true/false,
//                "msg": "error message", # optional
//            "file_path": "[real file path]"
//        }

        String path = request.getSession().getServletContext().getRealPath("upload");
        String suffix = "";
        ServerResponse targetFileName = iFileService.upload(file,path,suffix);
        //检查上传状态
        if (!targetFileName.isSuccess()){
            resultMap.put("success",false);
            resultMap.put("msg","上传失败");
        } else {
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
            resultMap.put("success",true);
            resultMap.put("msg","上传成功");
            resultMap.put("file_path",url);
            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
        }
        return resultMap;
    }
}